﻿/* Paul Bozzay
 * 6/30/2012
 * Mayhem Contest entry!
 * Type: Reaction
*/

/* Description: 
 * This reaction allows Mayhem users to run Command Prompt or .bat files in response to events.
 */

using System.Runtime.InteropServices;
using MayhemCore;
using MayhemWpf.ModuleTypes;
using MayhemWpf.UserControls;
using System;
using System.Runtime.Serialization;

namespace CMD
{
    [DataContract]
    [MayhemModule("Command Prompt", "Execute cmd.exe commands or .bat files.")]
    public class SetVolume : ReactionBase, IWpfConfigurable
    {
        [DataMember]
        private String Command;
        private bool CloseWindow;

        protected override void OnLoadDefaults()
        {
            Command = "";
            CloseWindow = false;
        }

        public override void Perform()
        {

            String strCmdText = "";

            //if the window should be closed on completion, append a /C to the string
            if (CloseWindow)
            {
                strCmdText = "/C " + Command;
            }
            //if not, go ahead and add a /k to leave it open
            else
            {
                strCmdText = "/k " + Command;
            }
            
            //since the world of commands and batch scripts is very expansive, it's a bit too difficult to catch the errors here.
            //In most cases it should show up in the window itself, so this just logs that an error occurred. 
            try
            {
                System.Diagnostics.Process.Start("CMD.exe", strCmdText);
            }
            catch (Exception)
            {
                ErrorLog.AddError(ErrorType.Failure, "The command was unable to execute.");
                return;
            }
        }

        public WpfConfiguration ConfigurationControl
        {
            get
            {
                return new SetCMDConfig(Command, CloseWindow);
            }
        }

        public void OnSaved(WpfConfiguration configurationControl)
        {
            var config = (SetCMDConfig)configurationControl;
            this.Command = config.Command;
            this.CloseWindow = (bool)config.closeWindow.IsChecked;
        }

        public string GetConfigString()
        {
            return string.Format("cmd.exe: {0}", Command);
        }
    }
}